package org.jflame.commons.json.jackson;

import org.jflame.commons.model.CallResult;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;

/**
 * CallResult序列化器,解决接口结果CallResult封装后使用@JsonView不生效问题.
 * <p>
 * <strong>注:需要禁用MapperFeature.DEFAULT_VIEW_INCLUSION</strong>
 * 
 * @author zyc
 */
@SuppressWarnings("rawtypes")
public class CallResultJsonSerializer extends JsonSerializer<CallResult> {

    private ObjectMapper objectMapper;

    public CallResultJsonSerializer(ObjectMapper _objectMapper) {
        objectMapper = _objectMapper;
    }

    @Override
    public void serialize(CallResult value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeStartObject();
        gen.writeStringField("message", value.getMessage());
        gen.writeNumberField("status", value.getStatus());
        if (serializers.getActiveView() != null && value.getData() != null) {
            gen.writeFieldName("data");
            gen.writeRawValue(objectMapper.writerWithView(serializers.getActiveView())
                    .writeValueAsString(value.getData()));
        } else {
            gen.writeObjectField("data", value.getData());
        }
        gen.writeEndObject();
    }

}
